// pages/friendVs/friendVs.js
const setting = require("../../http/env");
const httpApi = require("../../http/request"); //后续可以改为你自己的域名接口地址
let socket = null; //全局定义socket对象
let socketOpen = false; //是否开启websoket
let timer = null;
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //默认域名
    baseUrl: setting.baseUrl,
    //房主user_id
    home_user_id: 0,
    //答题匹配id
    quest_rule_id: 0,
    //上一个答题的ID
    pre_quest_game_id: 0,
    //需要返回
    nedd_back: 0,

    //房主
    initiate_user: "",
    //匹配人
    match_user: "",

    //是否分享了
    is_fx: true,
    //正在匹配中
    is_wait: false,
    //倒计时开始
    is_start: false,
    start_num: 3,
    showBaseUrl: false,
    showMatchBaseUrl: false,
    // 当前登录人
    user: {},
    // 次数用尽提示
    showRemind: false,
    limit_count_flag: 1
  },

  //数据回调
  mycallback(data) {
    var start = data.indexOf("["); // 第一次出现的位置
    var start1 = data.indexOf("{");

    if (start < 0) {
      start = start1;
    }
    if (start >= 0 && start1 >= 0) {
      start = Math.min(start, start1);
    }

    if (start >= 0) {
      var json = data.substr(start); //截取
      var json = JSON.parse(json);
      return json;
    } else {
      return "";
    }
  },

  //进行匹配
  send() {
    var that = this;
    if (socketOpen) {
      var param = {
        type: "friend",
        data: [
          {
            user_id: that.data.user.id,
            quest_rule_id: that.data.quest_rule_id,
            pre_quest_game_id: that.data.pre_quest_game_id,
          },
        ],
      };
      console.log("ws发送数据=====", param)
      socket.send({
        data: JSON.stringify(param),
        success: function (e) {
        },
      });
    }
  },

  reconnectWs() {
    this.setData({
      initiate_user: this.data.user,
      showBaseUrl: !this.data.user.headimg.includes('http'),
      home_user_id: '',
      quest_rule_id: '',
      pre_quest_game_id: '',
    });
    socket.close()
    this.connectWs()
  },

  closeRemind() {
    this.setData({
      showRemind: false,
    });
  },

  //接收信息
  geMessage(data) {
    var that = this;
    console.log("ws接到数据=====", data)
    //失败结果展示
    if (data && data[0] == "msg") {
      setTimeout(() => {
        wx.showToast({
          title: data[1],
          icon: "none",
          duration: 5000,
          success: function () {
            setTimeout(() => {
              wx.redirectTo({
                url: "../home/home",
              });
            }, 6000);
          },
        });
      }, 800)
    }
    // 需要停留在当前页面
    if (data && data[0] == "noMatch") {
      that.reconnectWs()
      setTimeout(() => {
        wx.showToast({
          title: data[1],
          icon: "none",
          duration: 5000,
        });
      }, 800)
    }
    //房主创建房间展示
    if (data && data[0] == "quest_rule_id") {
      var initiate_user = that.data.user;
      if (initiate_user.sorce > 999) {
        initiate_user.sorce = "999+";
      }

      that.setData({
        quest_rule_id: data[1],
        initiate_user: initiate_user,
        showBaseUrl: !initiate_user.headimg.includes('http')
      });
    }
    // 对战次数达到限制
    if (data && data[0] == "matchDataCount" && that.data.limit_count_flag == 1) {
      that.reconnectWs()
      that.setData({
        showRemind: true,
      });
    }
    //匹配人进入房间
    if (data && data[0] == "data") {
      var initiate_user = data[1].initiate_user;
      var match_user = data[1].match_user;

      if (initiate_user.sorce > 999) {
        initiate_user.sorce = "999+";
      }
      if (match_user.sorce > 999) {
        match_user.sorce = "999+";
      }

      that.setData({
        initiate_user: initiate_user,
        showBaseUrl: !initiate_user.headimg.includes('http'),
        match_user: match_user,
        showMatchBaseUrl: !match_user.headimg.includes('http'),
      });

      if (match_user.id) {
        //有匹配人
        that.setData({
          is_fx: false,
          is_wait: false,
          is_start: true,
        });
        //开始倒计时
        that.setStartTime();
      } else {
        clearInterval(timer);
        that.setData({
          is_fx: false,
          is_wait: true,
          is_start: false,
        });
      }
    }
    //开始比赛
    if (data && data[0] == "quest_game_id") {
      wx.redirectTo({
        url: "../start-fighting/start-fighting?quest_game_id=" + data[1] + '&initiate_user_id=' + this.data.initiate_user.id + '&match_user_id=' + this.data.match_user.id,
      });
    }
  },

  //开始比赛
  startGame(e) {
    var that = this;
    if (socketOpen) {
      var param = {
        type: "game",
        data: [
          {
            quest_rule_id: that.data.quest_rule_id,
          },
        ],
      };
      console.log("ws发送数据=====", param)
      socket.send({
        data: JSON.stringify(param),
        success: function (e) {
        },
      });
    }
  },

  // 开始倒计时器
  setStartTime() {
    var that = this;
    let timeCount = 3;
    timer = setInterval(() => {
      timeCount--;
      that.setData({
        start_num: timeCount,
      });
      if (timeCount <= 0) {
        clearInterval(timer);
        if (that.data.user.id == that.data.initiate_user.id) {
          that.startGame();
        }
      }
    }, 1000);
  },

  //退出提示
  back() {
    wx.redirectTo({
      url: "../home/home",
    });
  },

  //是否关闭了门店
  shopClose(e) {
    var that = this;
    var user = that.data.user;
    var params = {
      unitid: user.unitid,
    };
    httpApi.Post("/index/shopClose", params).then((res) => {

      if (res.is_close == 1 || res.is_end == 1) {
        wx.redirectTo({
          url: "../home/home",
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    //房主user_id
    var home_user_id = options.home_user_id ? options.home_user_id : 0;
    //答题匹配id
    var quest_rule_id = options.quest_rule_id ? options.quest_rule_id : 0;
    //分享的unitid
    var fx_unitid = options.fx_unitid ? options.fx_unitid : "";
    //分享的unitid_copy
    var fx_unitid_copy = options.fx_unitid_copy ? options.fx_unitid_copy : "";
    //分享人id
    var inviterId = options.inviterId || ''

    //上一个答题的id
    var pre_quest_game_id = options.quest_game_id ? options.quest_game_id : 0;
    //需要返回
    var nedd_back = options.nedd_back ? options.nedd_back : 0;

    //用户数据
    var user = wx.getStorageSync("userInfo");

    //参数判断
    if (!user || !user.id || !user.grade_id) {
      wx.redirectTo({
        url:
          "../home/home?quest_rule_id=" +
          quest_rule_id +
          "&home_user_id=" +
          home_user_id +
          "&unitid=" +
          fx_unitid +
          "&unitid_copy=" +
          fx_unitid_copy +
          "&inviterId=" +
          inviterId,
      });
      return
    }
    //是同一个用户，不能匹配自己
    if (home_user_id == user.id) {
      wx.redirectTo({
        url: "../home/home",
      });
      return
    }

    //保存数据
    that.setData({
      user: user,
      home_user_id: home_user_id,
      quest_rule_id: quest_rule_id,
      pre_quest_game_id: pre_quest_game_id,
      nedd_back: nedd_back,
      is_wait: pre_quest_game_id ? true : false,
      is_fx: pre_quest_game_id ? false : true,
      limit_count_flag: user.limit_count_flag,
    });

    this.connectWs()
  },

  connectWs() {
    if(this.data.user){
      //判断是否关闭
      this.shopClose();

      // 建立 WebSocket 连接
      socket = wx.connectSocket({
        url: setting.ws,
        header: {
          "content-type": "application/json",
        },
        success(res) {
          console.log("WebSocket 连接成功: ", res);
        },
        fail(err) {
          console.log("WebSocket 连接失败: ", err);
        },
      });
      // onOpen
      socket.onOpen(() => {
        console.log("打开 WebSocket 连接");
        socketOpen = true;
        //发送请求
        this.send();
        console.log(new Date());
      });
      // onError
      socket.onError((err) => {
        console.log("WebSocket 连接失败：", err);
        socketOpen = false;
      });
      // onClose
      socket.onClose((ret) => {
        console.log("断开 WebSocket 连接", ret);
        socketOpen = false;
      });
      //监听接收到的消息
      socket.onMessage((res) => {
        let msg = res.data;
        var getData = this.mycallback(msg);
        console.log("接收到的服务器消息", getData);
        this.geMessage(getData);
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      showRemind: false,
    });
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    if (!this.data.initiate_user) return
    if (!socketOpen && this.data.initiate_user.id === wx.getStorageSync("userInfo").id) {
      wx.showToast({
        title: '邀请已中断，请重新邀请好友对战',
        icon: 'none',
        duration: 5000
      })
      setTimeout(() => {
        this.back()
      }, 6000)
    } else if (!socketOpen && this.data.match_user.id === wx.getStorageSync("userInfo").id) {
      wx.showToast({
        title: '操作中断，您未能成功接受邀请。您可以尝试主动邀请好友对战',
        icon: 'none',
        duration: 5000
      })
      setTimeout(() => {
        this.back()
      }, 6000)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(timer);
    socket && socket.close();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    var that = this;
    var initiate_user = that.data.initiate_user;
    var quest_rule_id = that.data.quest_rule_id;
    var user = that.data.user;

    that.setData({
      is_fx: false,
      is_wait: true,
    });

    var path =
      "/pages/friendVs/friendVs?quest_rule_id=" +
      quest_rule_id +
      "&home_user_id=" +
      initiate_user.id +
      "&fx_unitid=" +
      user.unitid +
      "&fx_unitid_copy=" +
      user.unitid_copy + 
      "&inviterId=" + 
      wx.getStorageSync("userInfo").id +
      "&nedd_back=1";

      console.log('path---------', path)
    return {
      // title: initiate_user.nickname+'邀请您对战',
      title: app.globalData.shareInfo[e.from].title,
      imageUrl: app.globalData.shareInfo[e.from].imageUrl,
      path: path,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      },
    };
  },
});
